package com.woniuxy.exception;

import cn.hutool.json.JSONUtil;
import com.woniuxy.commons.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GloableExceptionHandler implements ErrorWebExceptionHandler {

	@Override
	public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
		Result<?> result = Result.getResult();
		if(ex instanceof MovieException) {
			MovieException me = (MovieException)ex;
			result.setMsg(me.getMessage()).setCode(me.getCode());
		} else if(ex instanceof Exception) 
			result.setCode(500).setMsg("系统错误");
		exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
		String json = JSONUtil.parse(result).toString();
		return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
			return  exchange.getResponse().bufferFactory().wrap(json.getBytes());
		}));
	}

}